package com.meisiabc.app.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.meisiabc.app.service.ProfileService;
import com.meisiabc.app.service.SmsCodeService;
import com.meisiabc.app.web.auth.AssertAuth;
import com.meisiabc.app.web.auth.SecurityContextHolder;
import com.meisiabc.support.Result;
import com.meisiabc.utils.MobileUtils;
import com.meisiabc.utils.Verify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.meisiabc.app.service.SmsCodeService.MODIFY;
import static com.meisiabc.app.service.SmsCodeService.PROFILE;

/**
 * Created by sunchangpeng
 */
@RestController
@RequestMapping("/profile")
public class ProfileController {
    @Autowired
    private SmsCodeService smsCodeService;
    @Autowired
    private ProfileService profileService;

    @GetMapping("/wechat")
    public Result wechatLogin(@RequestParam String code) {
        return Result.ok(profileService.wechatLogin(code));
    }

    @GetMapping("/sms")
    public Result sms(@RequestParam String mobile) {
        profileService.assertRegisted(mobile);
        smsCodeService.sendSms(PROFILE, mobile);
        return Result.ok();
    }

    @PostMapping("/login")
    public Result smsLogin(@RequestBody JSONObject loginForm) {
        String openid = loginForm.getString("openid");
        String mobile = loginForm.getString("mobile");
        String smsCode = loginForm.getString("sms_code");

        smsCodeService.verifySmsCode(PROFILE, mobile, smsCode);
        return Result.ok(profileService.smsLogin(openid, mobile));
    }

    @AssertAuth
    @GetMapping("/mobile/modify/sms")
    public Result modiftyMobileSms(@RequestParam String newMobile) {
        smsCodeService.sendSms(MODIFY, newMobile);
        return Result.ok();
    }

    @AssertAuth
    @PostMapping("/mobile/modify")
    public Result modiftyMobile(@RequestBody JSONObject loginForm) {
        String oldMobile = loginForm.getString("old_mobile");
        String newMobile = loginForm.getString("new_mobile");
        String smsCode = loginForm.getString("sms_code");

        Verify.isTrue(MobileUtils.isValidMobile(oldMobile), "请输入合法的手机号码");
        Verify.isTrue(MobileUtils.isValidMobile(newMobile), "请输入合法的手机号码");

        smsCodeService.verifySmsCode(MODIFY, newMobile, smsCode);

        String mobileValue = SecurityContextHolder.getContext().getMobile();
        String openid = SecurityContextHolder.getContext().getOpenid();

        Verify.isTrue(mobileValue.equals(oldMobile), "无法修改原手机号");

        return Result.ok(profileService.modiftyMobile(openid, oldMobile, newMobile));
    }
}
